﻿using System;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Design;
using System.Windows.Forms;

namespace Marmat.Forms
{

    /// <summary>
    /// 表示 颜色选择的编辑控件。
    /// </summary>
    [DefaultEvent("ValueChanged")]
    [ToolboxItem(true)]
    [ToolboxBitmap(typeof(ColorDialog))]
    public partial class ColorPickBox : EditControl
    {
        /// <summary>
        /// 初始化 Marmat.Forms.ColorPickBox 类的新实例。
        /// </summary>
        public ColorPickBox()
        {

            // 此调用是设计器所必需的。
            this.InitializeComponent();

            // 在 InitializeComponent() 调用之后添加任何初始化。
            this.BaseEdit = this.colorPickEdit1;
            this.colorPickEdit1.Properties.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.DisableTextEditor;
            colorPickEdit1.Name = "ColorPickEdit1";
        }

        public override BindingField BindingField
        {
            get
            {
                if (this.m_BindingField is null)
                    this.m_BindingField = new BindingField(this, nameof(Value), null, null, true, DataSourceUpdateMode.OnPropertyChanged, this);
                return this.m_BindingField;
            }
        }

        private BindingField m_BindingField;

        public Color Color
        {
            get => this._Color;
            set
            {
                this._Color = value;
                this.colorPickEdit1.EditValue = value;
            }
        }

        private Color _Color;

        [Bindable(true)]
        public new int Value
        {
            get => this._Value;
            set
            {
                if (!Equals(this.Value, value))
                {
                    this._Value = value;
                    this.Color = Color.FromArgb(value);
                    if (this.BindingField.IsBinding)
                    {
                        this.BindingField.WriteValue();
                    }
                }
            }
        }

        private int _Value;

        private void ColorPickEdit1_ColorChanged(object sender, EventArgs e)
        {
            Color Color = (Color)this.colorPickEdit1.EditValue;
            int ToArgb = Color.ToArgb();
            if (ToArgb != this.Value)
            {
                this.Value = ToArgb;
            }
        }
    }
}